package com.byzk.p2p.front.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.MD5;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.dto.BorrowApplyOff;
import com.byzk.p2p.admin.borrow.dto.Product;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.ProductService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.controller.FuionAccountController;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.money.dto.BorrowPayment;
import com.byzk.p2p.admin.order.dto.TenderOrder;
import com.byzk.p2p.admin.order.service.OrderService;
import com.byzk.p2p.admin.order.vo.TenderOrderVo;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.front.util.FrontUtil;


/**
 * 用户借款相关文件
 * @author liuchuan
 *
 */
@Controller
@Scope("prototype")
public class FrontTenderController extends BaseController{
	
	@Autowired
	private UserService userService ;
	@Autowired
	private BorrowService borrowService ;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private TenderService tenderService;
	@Autowired
	private UserAuthService userAuthService;
	@Autowired
	private ProductService productService;
	@Autowired
	private FuionAccountController fuionAccountController;
	
	/**
	 * 我要借款页
	 * @return
	 */
	@RequestMapping(value="/borrow")
	public ModelAndView borrow(Model model){
		User user = (User) session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		UserAccount account = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account = userAccountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account);
		model.addAttribute("auth", map);
		return new ModelAndView("/front/tender/list1");
	}
	
	/**
	 * 投标
	 * @param borrowId 借款标id
	 * @param amount 投标金额
	 * @param tenderPwd 验证码
	 * @throws Exception
	 */
	@RequestMapping(value="/front/tender/save",method=RequestMethod.POST)
	public void saveTender(@RequestParam(value="borrowId") Integer borrowId,
						   @RequestParam(value="amount") Double amount,
				           @RequestParam(value="password") String password) throws Exception{
		try {
			User user = (User) session.getAttribute("_user");
			user = userService.getById(user == null ?0:user.getId());
			if(user==null){
				redirect("/login");
				return ;
			}
			if("N".equals(user.getFuionAccount())){
				redirect("/account/register");
				return;
			}else{
				if(!user.getDealPassword().equals(MD5.GetMD5Code(password))){
					printJSON(new JsonMsg(2, "交易密码错误！"));
					return;					
				}
			}
			
			Borrow borrow = borrowService.detailBorrow(borrowId);
			BorrowApply borrowApply = borrowService.getBorrowApply(borrow.getBorrowApplyId());
			
			if(borrow.getProductId()==6){
				if("N".equals(user.getIsnew())){
					super.printJSON(new JsonMsg(3, "新手标每个用户只能投资一次！"));
					return;			
				}				
			}
			
			if (borrowApply.getUserId().equals(user.getId())) {
				printJSON(new JsonMsg(4, "该借款标由您发起，您自己不能投标！"));
				return;
			}				

			if(amount == null || borrow.getMin()==null || borrow.getMin()==0){
				if(amount%50 != 0){
					printJSON(new JsonMsg(5, "投标金额最低为"+borrow.getMin()+"元，请重新输入！"));
					return;
				}
			}else{
				if (amount<borrow.getMin() || amount%100 != 0) {
					printJSON(new JsonMsg(6, "投标金额最低为"+borrow.getMin()+"元，且最小投标金额必须是100.0的整数倍，请重新输入！"));
					return;
				}
			}  
			if (borrow.getNotTenderMoney() == null || borrow.getNotTenderMoney() <= 0d) {
				printJSON(new JsonMsg(7, "剩余可投金额不足，投标失败！"));
				return;
			}
			
			if(amount < borrow.getMin() || amount > borrow.getMax()){
				printJSON(new JsonMsg(8, "投资金额应大于"+borrow.getMin()+"小于"+borrow.getMax()));
				return;
			}
			if (amount > borrow.getNotTenderMoney()) {
				printJSON(new JsonMsg(9,"投资金额应该小于等于剩余可投金额！",borrow.getNotTenderMoney()));
				return;
			}
			Double money = tenderService.sumMoney(user.getId(), borrowId);
			if((money+amount) > borrow.getMax()){
				printJSON(new JsonMsg(10, "累计投资金额应小于"+borrow.getMax()));
				return;
			}
			//查询金账户用户可用余额
			UserAccount account = fuionAccountController.getFuionAccountBalance(user);
			if(account.getBalance() < amount ){
				printJSON(new JsonMsg(11, "您的投标金额超过金账户可用余额,请先充值!金账户可用余额为￥"+account.getBalance()+"元."));
				return;
			}

			UserAccount userAccount = userAccountService.getByUserId(user.getId());
			if(userAccount.getBalance() < amount ){
				printJSON(new JsonMsg(11, "您的投标金额超过账户可用余额,请先充值!账户可用余额为￥"+userAccount.getBalance()+"元."));
				return;
			}
			
/*			UserTender tender = new UserTender();
			tender.setUserId(user.getId());
			tender.setBorrowId(borrowId);
			tender.setChanges("N");
			tender.setRepayFinish("N");
			tender.setAmount(amount);
			tender.setCreateTime(new Date());
			tender.setTerminal("PC");
			tender.setIsAuto("N");
			tender.setCode(BaseUtil.generateCode(BaseUtil.TOUZI));
			
			tenderService.saveOrUpdateUserTender(tender);*/
			
			printJSON(new JsonMsg(-1, "投资成功！"));
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(17, "系统异常,请稍后再试！"));
		}

	}
	
	/**
	 * 新增自动投标
	 * @param tenderAuto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/front/auto/save",method=RequestMethod.POST)
	@ResponseBody
	public String saveAutoTender(@RequestBody TenderOrderVo tenderAuto) throws Exception{
		try {
			User user = (User) session.getAttribute("_user");
			user = userService.getById(user == null ?0:user.getId());
			
			if (tenderAuto.getMoney() == null) {
				printJSON(new JsonMsg(1, "请设置单次投标金额！"));
				return null;
			}
			if (tenderAuto.getMinPercent() == null) {
				printJSON(new JsonMsg(1, "请设置最小年化率"));
				return null;
			}
			if (tenderAuto.getMaxPercent() == null) {
				printJSON(new JsonMsg(1, "请设置最大年化率"));
				return null;
			}
			if (tenderAuto.getMinPercent() > tenderAuto.getMaxPercent()) {
				printJSON(new JsonMsg(1, "年化率设置有误"));
				return null;
			}
			if (tenderAuto.getMinPeriod() == null) {
				printJSON(new JsonMsg(1, "请设置最小期限"));
				return null;
			}
			if (tenderAuto.getMaxPeriod() == null) {
				printJSON(new JsonMsg(1, "请设置最大期限"));
				return null;
			}
			if (tenderAuto.getMinPeriod() > tenderAuto.getMaxPeriod()) {
				printJSON(new JsonMsg(1, "借款期限设置有误"));
				return null;
			}
			if (tenderAuto.getReserveFund() == null) {
				printJSON(new JsonMsg(1, "请设置保留可用余额"));
				return null;
			}
			UserAccount userAccount = userAccountService.getByUserId(user.getId());
			if (tenderAuto.getReserveFund()>userAccount.getBalance()-tenderAuto.getMoney()) {
				printJSON(new JsonMsg(1, "保留可用余额金额有误，请参考右侧公式!"));
				return null;
			}
			if(userAccount.getLevel()<2){
				printJSON(new JsonMsg(1, "您暂无自动投标权限！"));
				return null;
			}
			tenderAuto.setUserId(user.getId());
			tenderAuto.setReserveFund(tenderAuto.getReserveFund() == null?0.00:tenderAuto.getReserveFund());
			orderService.saveOrUpdate(tenderAuto);
			printJSON(new JsonMsg(-1, "设置成功！"));
		} catch (Exception e) {
			super.printJSON(new JsonMsg(0, "服务器异常,请稍后再试！"));
		}
		return null;
	}
	
	/**
	 * 开启关闭自动投标
	 * @param id
	 * @param status
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/front/auto/change")
	public String openAutoTender(@RequestParam("id") Integer id,@RequestParam("status") Integer status) throws Exception{
		User user = (User) session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		TenderOrder order=orderService.selectByOrderId(id);
		order.setStatus(status);
		if(status==0){
			order.setOrder(0);
		}else{
			order.setOrder(orderService.lastId()+1);
		}
		orderService.updateOrder(order);
		printJSON(new JsonMsg(-1, "操作成功！"));
		return null;
	}
	/**
	 * 用户申请借款
	 * @throws Exception
	 */
	@RequestMapping("/front/apply/tender")
	public void borrow_apply() throws Exception{
		User user = (User) session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		if(user == null){
			printJSON(new JsonMsg(1, "请先登录，再申请借款！"));
			return ;
		}
		if("N".equals(user.getFuionAccount())){
			printJSON(new JsonMsg(2, "请先开通第三方托管账户，再申请借款！"));
			return ;
		}else{
			printJSON(new JsonMsg(-1, "操做成功！"));
		}
	}
	
	/**
	 * 借款申请页
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/front/borrow/apply/{type}",method=RequestMethod.GET)
	public String borrowApply(Model model, @PathVariable String type) throws Exception{
		User user = (User) session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		if("N".equals(user.getFuionAccount())){
			return redirect("/account/register");
		}
		UserAccount account = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account = userAccountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account);
		model.addAttribute("auth", map);
		model.addAttribute("user", user);
		model.addAttribute("type", FrontUtil.borrowApplyMap.get(type));
		//产品类型
		List<Product> productList = productService.productList();
		model.addAttribute("productList", productList);
		return "/front/tender/apply1";
	}
	
	/**
	 * 借款申请
	 * @param borrowApply 借款申请信息
	 */
	@RequestMapping("/front/borrow/add")
	public void borrowApply(@ModelAttribute("borrowApply") BorrowApply borrowApply) throws Exception{
		User frontUser = (User) session.getAttribute("_user");
		frontUser = userService.getById(frontUser == null ?0:frontUser.getId());
		try {
			if (frontUser == null) {
				printJSON(new JsonMsg(1, "请先登录，再申请！"));
				return;
			}
			if(StringUtils.isBlank(frontUser.getRealname())) {
				printJSON(new JsonMsg(7, "请先实名认证，再申请！"));
				return;
			}
			if (borrowApply == null) {
				printJSON(new JsonMsg(2, "借款失败！"));
				return;
			}
			try {
				Double amount=Double.parseDouble(borrowApply.getAmount());
				if (amount == null || amount <=0d) {
					printJSON(new JsonMsg(3, "借款金额填写有误！"));
					return;
				}
			} catch (Exception e) {
				printJSON(new JsonMsg(3, "金额填写过大，请重新填写"));
			}
			if (StringUtils.isBlank(borrowApply.getApplyType())) {
				printJSON(new JsonMsg(4, "请选择借款类型！"));
				return;
			}
			if (borrowApply.getDate() == null) {
				printJSON(new JsonMsg(5, "请填写借款期限！"));
				return;
			}
			borrowApply.setUserId(frontUser.getId());
			borrowApply.setStatus(1);
			borrowApply.setCreateTime(new Date());
			borrowApply.setTerminal("PC");
			Integer i = borrowService.saveOrUpdateBorrowApply(borrowApply);
			if (i>0) {
				printJSON(new JsonMsg(-1, "借款申请成功！", null));
			}else{
				printJSON(new JsonMsg(0, "借款申请失败！", null));
			}
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	/**
	 * 线下借款申请
	 * @param borrowApply 借款申请信息
	 */
	@RequestMapping(value ="/front/borrow/off/add",method=RequestMethod.POST)
	@ResponseBody
	public void borrowApplyOff(@RequestBody BorrowApplyOff borrowApplyOff) throws Exception{
		try {
			if (borrowApplyOff == null) {
				printJSON(new JsonMsg(2, "借款失败！"));
				return;
			}
			try {
				Double amount=borrowApplyOff.getAmount();
				if (amount == null || amount <=0d) {
					printJSON(new JsonMsg(3, "借款金额填写有误！"));
					return;
				}
			} catch (Exception e) {
				printJSON(new JsonMsg(3, "金额填写过大，请重新填写"));
			}
			if(StringUtils.isBlank(borrowApplyOff.getInvitCode())){
				printJSON(new JsonMsg(4, "内部邀请码不能为空！"));
				return;				
			}else{
				List<User> userList=userService.getUserByInviteCode(borrowApplyOff.getInvitCode());
				if(userList.size()<1){
					printJSON(new JsonMsg(5, "内部邀请码不存在！"));
					return;						
				}
			}

			borrowApplyOff.setCreateTime(new Date());
			Integer i = borrowService.saveOrUpdateBorrowApplyOff(borrowApplyOff);
			if (i>0) {
				printJSON(new JsonMsg(-1, "借款申请成功！", null));
			}else{
				printJSON(new JsonMsg(0, "借款申请失败！", null));
			}
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	} 
	
//	/**
//	 * 投标
//	 * @param borrowId 借款标id
//	 * @param amount 投标金额
//	 * @param tenderPwd 验证码
//	 * @throws Exception
//	 */
//	@RequestMapping(value="/front/tender/save1",method=RequestMethod.POST)
//	public void SaveTender() throws Exception{
//		try {
//			//获取请求参数值
//			Integer User_id = Integer.parseInt(request.getParameter("userId"));
//			String password = request.getParameter("password");
//			Integer borrowId = Integer.parseInt(request.getParameter("borrowId"));
//			Double amount = Double.parseDouble(request.getParameter("amount"));
//			
//			System.out.println("请求参数列表：用户编号{"+User_id+"金额【"+amount+"投标编号【"+borrowId+"");
//			
//			User user = userService.getById(User_id);
//			
//			if(user==null){
//				redirect("/login");
//				return ;
//			}
//			if("N".equals(user.getFuionAccount())){
//				redirect("/account/register");
//				return;
//			}else{
//				if(!user.getDealPassword().equals(MD5.GetMD5Code(password))){
//					printJSON(new JsonMsg(2, "交易密码错误！"));
//					return;					
//				}
//			}
//			
//			Borrow borrow = borrowService.detailBorrow(borrowId);
//			BorrowApply borrowApply = borrowService.getBorrowApply(borrow.getBorrowApplyId());
//			
//			if(borrow.getProductId()==6){
//				if("N".equals(user.getIsnew())){
//					super.printJSON(new JsonMsg(3, "新手标每个用户只能投资一次！"));
//					return;			
//				}				
//			}
//			
//			if (borrowApply.getUserId().equals(user.getId())) {
//				printJSON(new JsonMsg(4, "该借款标由您发起，您自己不能投标！"));
//				return;
//			}				
//
//			if(amount == null || borrow.getMin()==null || borrow.getMin()==0){
//				if(amount%50 != 0){
//					printJSON(new JsonMsg(5, "投标金额最低为"+borrow.getMin()+"元，请重新输入！"));
//					return;
//				}
//			}else{
//				if (amount<borrow.getMin() || amount%100 != 0) {
//					printJSON(new JsonMsg(6, "投标金额最低为"+borrow.getMin()+"元，且最小投标金额必须是100.0的整数倍，请重新输入！"));
//					return;
//				}
//			}  
//			if (borrow.getNotTenderMoney() == null || borrow.getNotTenderMoney() <= 0d) {
//				printJSON(new JsonMsg(7, "剩余可投金额不足，投标失败！"));
//				return;
//			}
//			
//			if(amount < borrow.getMin() || amount > borrow.getMax()){
//				printJSON(new JsonMsg(8, "投资金额应大于"+borrow.getMin()+"小于"+borrow.getMax()));
//				return;
//			}
//			if (amount > borrow.getNotTenderMoney()) {
//				printJSON(new JsonMsg(9,"投资金额应该小于等于剩余可投金额！",borrow.getNotTenderMoney()));
//				return;
//			}
//			Double money = tenderService.sumMoney(user.getId(), borrowId);
//			if((money+amount) > borrow.getMax()){
//				printJSON(new JsonMsg(10, "累计投资金额应小于"+borrow.getMax()));
//				return;
//			}
//			//查询金账户用户可用余额
//			UserAccount account = fuionAccountController.getFuionAccountBalance(user);
//			if(account.getBalance() < amount ){
//				printJSON(new JsonMsg(11, "您的投标金额超过金账户可用余额,请先充值!金账户可用余额为￥"+account.getBalance()+"元."));
//				return;
//			}
//
//			UserAccount userAccount = userAccountService.getByUserId(user.getId());
//			if(userAccount.getBalance() < amount ){
//				printJSON(new JsonMsg(11, "您的投标金额超过账户可用余额,请先充值!账户可用余额为￥"+userAccount.getBalance()+"元."));
//				return;
//			}
//			
///*			UserTender tender = new UserTender();
//			tender.setUserId(user.getId());
//			tender.setBorrowId(borrowId);
//			tender.setChanges("N");
//			tender.setRepayFinish("N");
//			tender.setAmount(amount);
//			tender.setCreateTime(new Date());
//			tender.setTerminal("PC");
//			tender.setIsAuto("N");
//			tender.setCode(BaseUtil.generateCode(BaseUtil.TOUZI));
//			
//			tenderService.saveOrUpdateUserTender(tender);*/
//			
//			printJSON(new JsonMsg(-1, "投资成功！"));//
//			TestThread te = new TestThread();
//			te.setAmount(amount);
//			te.setBorrowId(borrowId);
//			te.setUserId(User_id);
//			te.setPassword(password);
//			te.setThread(te);
//	        String	backStr = WebUtils.sendHttp(Config.server_url+"/fuion/transfer/freezen",te);
//		} catch (Exception e) {
//			e.printStackTrace();
//			printJSON(new JsonMsg(17, "系统异常,请稍后再试！"));
//		}

//	}
	
}
